package china.z.console.config.datasources.dynamic;

import china.z.console.common.exception.CustomException;
import china.z.console.config.datasources.DS;
import china.z.console.config.datasources.DataSourceContextHolder;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author zengyz
 * @date 2018-01-01
 *  切面拦截
 */
@Aspect
@Component
public class DynamicDataSourceAspect {

    @Before(value = "@annotation(china.z.console.config.datasources.DS)")
    public void beforeSwitchDataSource(JoinPoint point){

        //获得当前访问的class
        Class<?> className = point.getTarget().getClass();
        //获得访问的方法名
        String methodName = point.getSignature().getName();
        //得到方法的参数的类型
        Class[] argClass = ((MethodSignature)point.getSignature()).getParameterTypes();

        String dataSource = DataSourceContextHolder.FIRST_DS;
        try {
            // 得到访问的方法对象
            Method method = className.getMethod(methodName, argClass);
            // 判断是否存在@DataSource注解
            if (method.isAnnotationPresent(DS.class)) {
                DS annotation = method.getAnnotation(DS.class);
                // 取出注解中的数据源名
                dataSource = annotation.value();
            }
        }catch (Exception e){
            throw new CustomException("DynamicDataSourceAspect.java 动态数据源Before失败", e);
        }
        DataSourceContextHolder.setDatasource(dataSource);
    }

    @After(value = "@annotation(china.z.console.config.datasources.DS)")
    public void afterSwitchDataSource(JoinPoint point){
        DataSourceContextHolder.clearDB();
    }
}
